# -*- encoding: utf-8 -*-
'''
Created on 2011-04-20

@author: quermit
'''
import json
import urllib2
import logging

from PyQt4.QtCore import QThread


log = logging.getLogger(__name__)


class IndexListFetcher(QThread):
    
    def __init__(self, parent, url):
        super(IndexListFetcher, self).__init__(parent)
        self.__url = url
        
    def run(self):
        log.debug("Fetching index list...")
        
        self.__error = None
        self.__result = []
        
        try:
            req = urllib2.urlopen(self.__url, timeout=10)
            data = req.read()
        except Exception, e:
            self.__error = "Request error: %s" % e
            log.error(self.__error)
            return
        
        try:
            indexes = json.loads(data)
        except ValueError, e:
            self.__error = "Parse error: %s" % e
            log.error(self.__error)
            return
        
        for idx in indexes:
            data = IndexData(idx["name"], idx["host"], idx["port"], idx["topic"])
            self.__result.append(data)
            
        log.debug("Indexes fetched: %d" % len(self.__result))
            
    def get_error(self):
        return self.__error
    
    def get_result(self):
        return self.__result
        

class IndexData(object):
    
    def __init__(self, name, host, port, topic):
        self.name = name
        self.host = host
        self.port = port
        self.topic = topic
